<?php
// +-------------------------------------------------------------------------------
// | DingZone [ A Rapid Development Framework For Dingtalk ]
// +-------------------------------------------------------------------------------
// | DatabaseBackupService.php v1.0
// |
// | Copyright (c) 2014-2018 http://www.heimalanshi.com All rights reserved.
// | Author : Jie
// | Date : 2018-10-13
// +-------------------------------------------------------------------------------


namespace app\core\service;


use app\extend\db\TableBackupHelper;
use app\extend\db\TableInfoHelper;

class DatabaseBackupService {

    /**
     * 获取备份文件保存目录
     *
     * @return string
     */
    public static function getBackupDirPath() {
        $dirPath = ROOT_PATH . "backups" . DS . "database" . DS . date('Ymd');

        if (!is_dir($dirPath)) {
            mkdir($dirPath, 0777, true);
        }

        return $dirPath;
    }

    /**
     * 备份数据表
     *
     * @param $name
     * @throws \think\Exception
     */
    public static function backupTable($name) {
        TableBackupHelper::backup($name, self::getBackupDirPath());
    }

    /**
     * 备份模块相关的数据表
     *
     * @param $moduleName
     * @throws \think\Exception
     */
    public static function backupModuleTables($moduleName) {
        $tables = TableInfoHelper::getTables($moduleName);
        foreach ($tables as $table) {
            TableBackupHelper::backup($table, self::getBackupDirPath());
        }
    }

    /**
     * 备份数据库
     *
     * @throws \think\Exception
     */
    public static function backupDatabase() {
        $tables = TableInfoHelper::getTables();
        foreach ($tables as $table) {
            TableBackupHelper::backup($table, self::getBackupDirPath());
        }
    }

}